from django.template import Context, loader
from django.http import HttpResponse
from indexed.models import Files
from time import time#, sleep

from django.utils import simplejson

from django.db.models import Q
from django.shortcuts import render_to_response

def get_res_dict(response_dict):
    query = response_dict['q']
    qset = (Q(name__startswith=query) | Q(path__startswith=query))
    time_res=time()
    results=Files.objects.filter(qset).distinct()
    response_dict.update({'time_res' : "%*.*f"%(5,6, time()-time_res), 'len_res': len(results) })
    out_results = ['']
    for i in xrange(len(results)):
        out_results.append(str(results[i]))
    response_dict.update({'results' : out_results})
    return response_dict

def refresh(request):
    response_dict = {}
    query = request.GET.get('p', False)
    response_dict.update({'q': query})
    response_dict = get_res_dict(response_dict)
    return render_to_response("indexed/res.html", response_dict)

def index(request):
    object_list = Files.objects.order_by('name')[:20]
    t = loader.get_template('indexed/files_list.html')
    c = Context({
        'object_list': object_list,
    })
    return HttpResponse(t.render(c))

def search(request):
    return render_to_response("indexed/search.html", {})